﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using pwblog.Entities;

namespace pwblog.DataAccess
{
    public class AccountDao
    {
        ManageBlogDataContext dataContext;

        public AccountDao()
        {
            dataContext = new ManageBlogDataContext();
        }

        public Account GetAccount(string username, string password)
        {
            var accounts = dataContext.Accounts.Where(item => item.UserName == username && item.Password == password);
            return accounts.First();
        }

        /// <summary>
        /// lay tat ca cac account
        /// </summary>
        /// <returns></returns>
        public Account[] GetAccounts()
        {
            return new ManageBlogDataContext().Accounts.ToArray();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="newAccount"></param>
        public void UpdateAccount(Account newAccount)
        {
            var oldAccount = dataContext.Accounts.Single(item => item.UserName == newAccount.UserName);
            oldAccount.Birthday = oldAccount.Birthday;
            oldAccount.Address = oldAccount.Address;
            oldAccount.Roles = oldAccount.Roles;
            oldAccount.Password = newAccount.Password;
            oldAccount.NumberOfArticle = newAccount.NumberOfArticle;

            dataContext.SubmitChanges();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        internal Account[] GetAccountByUserName(string userName)
        {
            return dataContext.Accounts.Where(item => item.UserName == userName).ToArray();
        }

        /// <summary>
        /// Get account by Email
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        internal Account GetAccountByEmail(string email)
        {
            return dataContext.Accounts.SingleOrDefault(item => item.Address == email);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="account"></param>
        internal void DeleteAccount(Account account)
        {
            dataContext.Accounts.DeleteOnSubmit(account);
            dataContext.SubmitChanges();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="newAccount"></param>
        internal void InsertAccount(Account newAccount)
        {
            dataContext.Accounts.InsertOnSubmit(newAccount);
            dataContext.SubmitChanges();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        internal Account FindAccount(string username)
        {
            return dataContext.Accounts.SingleOrDefault(item => item.UserName == username);
        }
    }
}